package com.etheart.lyric.htmlparser.service.baidu;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.springframework.stereotype.Service;

import com.etheart.framework.core.util.RegexUtils;
import com.etheart.lyric.htmlparser.util.HtmlparserUtils;
import com.etheart.model.entity.Resource;
import com.etheart.model.entity.Singer;
import com.etheart.model.entity.Song;

@Service("htmlparse_BaiduSongParseService")
public class BaiduSongParseService {
	private static final Log logger = LogFactory
			.getLog(BaiduSongParseService.class);

	public Song fillSong(Parser parser, Song song) throws ParserException {
		
		//解析歌词下载地址
		String lrcUrl = getLrcUrl(parser); 
		song.setLrcUrl(lrcUrl);
	
		//得到resource
		Resource resource = getResouce( song);
		if (resource!=null) {
			song.getResources().add(resource);
		}
		
		return song;
	}
	
	private String getLrcUrl(Parser parser) throws ParserException {
		parser.reset();
//		<div class="listen_singerintro_name">
//        <p><strong>Peter Buffett</strong></p>
//        <p>Peter Buffett</p>
//    </div>
		NodeFilter filter = new AndFilter(new TagNameFilter("a"),new HasAttributeFilter("href","#"));  
		NodeList nodeList = parser.parse(filter);
		for (int i = 0; i < nodeList.size(); i++) {
			Node node = nodeList.elementAt(i);
			if (node.toHtml().indexOf("下载LRC歌词")!=-1) {
				String html = ((Tag)node).getAttribute("class");
				//down-lrc-btn { 'href':'/data2/lrc/12637086/12637086.lrc'
				return RegexUtils.getMatcheGroup(".*:'(.*lrc)'.*", html);
			}
		}
		return "";
	}

	public Resource getResouce( Song song) throws ParserException {
		String url = "http://ting.baidu.com/song/"+song.getNetId()+"/download";
 		//得到歌曲下载地址
		Parser parser = HtmlparserUtils.getParserFromNetWork(url);
			String downUrl = getDownUrl(parser);
			Resource resource = new Resource();
			resource.setSong(song);
			resource.setUrl(downUrl);
			return resource;
		
	}




	private String getDownUrl(Parser parser) throws ParserException {
		parser.reset();
		NodeFilter filter = new AndFilter(new TagNameFilter("a"),new HasAttributeFilter("class", "btn-download"));
		NodeList nodeList = parser.parse(filter);
		if ( nodeList.size()<=0) {
			return null;
		}
		Tag tag = (Tag) nodeList.elementAt(0);
		return tag.getAttribute("href");
	}

	
}
